#!/usr/bin/env python3
"""
数据库连接测试脚本
"""

import sys
from sql_pools.mysql_config import MySQLClient
from tools.log_util import INFO, ERROR, WARNING


def connect_database():
    """连接到MySQL数据库并测试连接"""
    # 数据库连接信息
    DB_HOST = '10.141.194.72'
    DB_PORT = 23306
    DB_USER = 'viu_root'
    DB_PASSWORD = 'myviu_4359'
    DB_NAME = 'd_cgboss_info'
    
    print(f"正在连接数据库: {DB_HOST}:{DB_PORT}/{DB_NAME}...")
    
    try:
        # 创建MySQL客户端实例
        client = MySQLClient(
            host=DB_HOST,
            port=DB_PORT,
            user=DB_USER,
            password=DB_PASSWORD,
            database=DB_NAME
        )
        
        # 测试连接 - 执行一个简单查询
        result = client.execute_query("SELECT 1 AS test")
        if result and result[0]['test'] == 1:
            print("✅ 数据库连接成功!")
        
        # 获取数据库表信息
        tables = client.execute_query("SHOW TABLES")
        if tables:
            print(f"\n数据库包含 {len(tables)} 个表:")
            for i, table in enumerate(tables, 1):
                table_name = list(table.values())[0]
                print(f"  {i}. {table_name}")
                
            # 获取第一个表的结构
            if len(tables) > 0:
                first_table = list(tables[0].values())[0]
                print(f"\n表 '{first_table}' 的结构:")
                columns = client.execute_query(f"DESCRIBE {first_table}")
                print("| 字段名 | 类型 | NULL | 键 | 默认值 | 其他 |")
                print("|--------|------|------|-----|--------|------|")
                for col in columns:
                    print(f"| {col['Field']} | {col['Type']} | {col['Null']} | {col['Key']} | {col['Default'] or 'NULL'} | {col['Extra']} |")
                
                # 获取表中的记录数
                count = client.execute_query(f"SELECT COUNT(*) as count FROM {first_table}")
                print(f"\n表 '{first_table}' 包含 {count[0]['count']} 条记录")
                
                # 显示表的前5条记录
                if count[0]['count'] > 0:
                    print(f"\n表 '{first_table}' 的前5条记录:")
                    records = client.execute_query(f"SELECT * FROM {first_table} LIMIT 5")
                    if records:
                        # 打印列名
                        cols = list(records[0].keys())
                        print("| " + " | ".join(cols) + " |")
                        print("| " + " | ".join(["----" for _ in cols]) + " |")
                        
                        # 打印数据
                        for record in records:
                            print("| " + " | ".join([str(record[col]) for col in cols]) + " |")
        
        return True
    except Exception as e:
        print(f"❌ 数据库连接失败: {str(e)}")
        return False


if __name__ == "__main__":
    connect_database() 